package org.mspring.mlog.task;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.dao.ArticleDao;
import org.mspring.mlog.entity.Article;
import org.mspring.mlog.entity.em.ArticleStatus;
import org.mspring.mlog.service.ConfigService;
import org.mspring.nbee.common.sitemap.WebSitemapGenerator;
import org.mspring.nbee.common.utils.PropertyConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * @author Gao Youbo
 * @since 2015-01-28 13:15
 */
@Component
public class SitemapTask {
    private static final Logger LOG = LoggerFactory.getLogger(SitemapTask.class);

    private ArticleDao articleDao;
    private ConfigService configService;
    private PropertyConfigurer propertyConfigurer;

    public void doTask() throws Exception {
        String webRoot = propertyConfigurer.getString("web.root");
        if (StringUtils.isBlank(webRoot)) {
            LOG.warn("无法生成sitemap, web.root未知。");
            return;
        }
        File root = new File(webRoot);
        if (!root.exists() || !root.isDirectory()) {
            LOG.warn("无法生成sitemap, web.root配置错误");
            return;
        }
        String siteurl = configService.getConfigValue("base", "siteurl");
        if (StringUtils.isBlank(siteurl)) {
            LOG.warn("无法生成sitemap, 请先设置base.siteurl");
            return;
        }
        WebSitemapGenerator generator = WebSitemapGenerator.builder(siteurl, root).build();
        List<Article> articleList = articleDao.listAll();
        for (Article article : articleList) {
            if (article.getStatus() == ArticleStatus.NORMAL) {
                generator.addUrl(siteurl + "/article/" + article.getId());
            }
        }
        generator.write();
    }

    @Autowired
    public void setArticleDao(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    @Autowired
    public void setConfigService(ConfigService configService) {
        this.configService = configService;
    }

    @Autowired
    public void setPropertyConfigurer(PropertyConfigurer propertyConfigurer) {
        this.propertyConfigurer = propertyConfigurer;
    }
}
